package com.zhiwei.jenkins.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CertNoUtil {
    private static final int invalidAge = -1; // 非法的年龄，用于处理异常。

    /**
     * 根据身份证号码计算年龄
     * @param certNo 考虑到15位身份证（不一定存在）
     * @return
     */
    public static int getAgeByIDNumber(String certNo) {
        String dateStr;
        if (15 == certNo.length()) {
            dateStr = "19" + certNo.substring(6, 12);
        } else if (18 == certNo.length()) {
            dateStr = certNo.substring(6, 14);
        } else {
            return invalidAge;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            Date birthday = simpleDateFormat.parse(dateStr);
            return getAgeByDate(birthday);
        } catch (Exception e) {
            return invalidAge;
        }
    }

    /**
     * 根据生日计算年龄
     * @param birthday
     * @return
     */
    public static int getAgeByDate(Date birthday) {
        Calendar calendar = Calendar.getInstance();
        if ((calendar.getTimeInMillis() - birthday.getTime()) < 0L) {
            return invalidAge;
        }

        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayOfMonthNow = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.setTime(birthday);

        int yearBithday = calendar.get(Calendar.YEAR);
        int monthBithday = calendar.get(Calendar.MONTH);
        int dayOfMonthBithday = calendar.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBithday;

        if (monthNow <= monthBithday && monthNow == monthBithday && dayOfMonthNow < dayOfMonthBithday ||
                monthNow < monthBithday ) {
            age--;
        }

        return age;
    }

    public static void main(String[] args) {
        System.out.println(getAgeByIDNumber("4000000000000"));
    }

}
